<?php

class indexController extends Controller {

	private $tablePage = 'page';
	private $userTable = 'user';
	private $documentTable = 'document';

	public function initialize() {
		$this->IsLoggedin(); // this functions has to be called 
		$this->view->title = 'Schagen - Adminsitrator';
		$this->view->layoutPath = 'template';
		$this->view->templateUrl = 'template';
		$this->view->add_css('back/back-main.css');
		$this->view->add_js('jquery-min.js');
	}

	public function indexAction() {
		
		$this->view->setLayout('admin');
		$this->getAnnouncements();
		$this->getColor();
		$this->view->show();
		
		if(isset($_GET['kleur'])){
			$this->updateColor();
		}
	}

	//-------------- Begin Page edit functions --------------//

	public function editpageAction(){
		$this->view->title = 'Schagen - Pagina Bewerken';
		$this->view->layoutPath = 'template';
		$this->view->templateUrl = 'template';

		$this->view->add_css('back/back-main.css');
		$this->view->add_js('color.jquery.js');
		$this->view->add_js('jMenu.js');
		$this->view->add_js('ckeditor/ckeditor.js');
		$this->view->add_js('jquery-min.js');
		$this->view->setLayout('admin');

		$this->getPages();
		$this->getPageContent();
		$this->check();
		$this->removePage();
		
		$this->view->show();

	}

	public function getPages(){
		//if($_SESSION['isAdmin'] == 1){
		//	$sql = "SELECT * FROM `page`";
		//	$result = DBH::getInstance()->query($sql);
		//	$amenu = mysql_fetch_object($result);
		//}


		$amenu = DBH::getInstance()->read_all("page");
		$this->view->menu = $amenu;
	}

	public function getPageContent() {
		$whereClause =  $_GET['id'];
		//Build the Query, run it and fetch it
		$sql = "id = '$whereClause'";
		
		$result = DBH::getInstance()->read($sql, $this->tablePage);
		$this->view->page_content = $result;
			
	}

	 /*
     * checking if $_POST global is set and make a new stdClass with POST values
     */
    public function check(){
    	if( isset ( $_POST['content'], $_GET['id'] ) ){
   
    		$data = new stdClass;
    		$data->content = stripcslashes($_POST['content']);
    		$data->visible = $_POST['visible'];
    		$where = "id = '" . $_GET['id'] . "'";
    		//$this->view->header_page = $_POST['page_name'];
    		
    		$this->update_content( $data, $where );
    	}
    	
    }
    
    /*
     * @param object $data
     */
    public function update_content( $data, $where ){
    	
    	if( isset( $data ) == false ) {
			
			log::fatal( 'Data not sent to databse', $this, 'update_content()' );
		}

		if(!DBH::getInstance()->update( $data, $where, "page" )){
			$this->view->message = "Er is iets fout gegaan tijden het update";
			return;
		}
		
		$this->view->result = true;
    }

    public function removePage(){
		if(isset($_GET['remove'])){
			$sql = "`id` = ". $_GET['remove'];
			if(!DBH::getInstance()->delete($sql, "page")){
				log::fatal("Unable to remove page", $this, "removePage()");
			}
			header("Location: ./editpage?id=3");
		}
	}

	//-------------- End Page edit functions ---------------//

	//---------------Begin Page Create functions------------//

	public function addpageAction() {
		$this->view->title = 'Schagen - Pagina Toevoegen';
		$this->view->layoutPath = 'template';
		$this->view->templateUrl = 'template';

		$this->view->add_css('back/back-main.css');
		$this->view->setLayout('admin');
		if( isset( $_POST['btn_AddPage'] )){
			$this->createPageRow();
			if( $_POST['parent_id'] == "0"){ // chose between create parent or child page
				$this->createParentPage($_POST['title']);
			}elseif( $_POST['group'] != 0){ // page is protected no need to create files
				break;
			}else{
				$this->createChildPage($_POST['title'], $_POST['parent_id']);
			}
		}

		$this->getUsers();
		$this->getGroups();
		$this->getSubPages();
		$this->view->show();
	}

	public function getSubPages(){

		$sql = "SELECT id, name, parent_id FROM `page` WHERE `parent_id` = 0";
		$result = DBH::getInstance()->query($sql, 'page');

		$subPages = array();
		while ($subpage = mysql_fetch_object($result)) {
    		$subPages[] = $subpage;
		}

		$this->view->subPages = $subPages;
	}

	public function createPageRow() {
			$title = $_POST['title'];

		    $object = new stdClass();

			$object->name = 		$title;
			$object->url  = 		preg_replace('/\s+/', '', $title);
			$object->visible = 		$_POST['visible'];
			$object->protected = 	$_POST['protected'];
			$object->parent_id = 	$_POST['parent_id'];
			$object->group_id = 	$_POST['group'];
			//$object->user_id = 		
			//TODO add userid in object and user need to be groupid
			if(!DBH::getInstance()->create($object, "page")){
				return false;
			}
			return true;		
		
	}
	/*
	* Function to create parent page
	* @param String pageTitle
	* @return boolean true
	*/
	public function createParentPage($pageTitle) {
			$CTdirStructure = "controller/" . preg_replace('/\s+/', '', strtolower($pageTitle));
			$VWdirStructure = "view/" . preg_replace('/\s+/', '', strtolower($pageTitle));
			
			fileHandler::getInstance()->makeDir( $CTdirStructure, 0777 ); //create controller folder
			fileHandler::getInstance()->copyFile($CTdirStructure, "indexController.php", "controller/defaultController.php"); //copy DefaultController into new controller folder
			
			fileHandler::getInstance()->makeDir($VWdirStructure, 0777 ); //create view folder
			fileHandler::getInstance()->copyFile($VWdirStructure, "index.php", "view/defaultIndex.php");

			$this->view->result = true;
	}

	/*
	* Function to create child page
	* @param String pageTitle
	* @param int parent id
	* @return boolean true
	*/
	public function createChildPage($pageTitle, $parent_id){
			$title = preg_replace('/\s+/', '', $pageTitle);
			$parent = $this->getParents($parent_id); // get the parent page name
			foreach ($parent as $value) {
				$CTdirStructure = "controller/" . $value->name . "/indexController.php"; //create CT dir structure
				$VWdirStructure = "view/" . $value->name . "/" . $title . ".php";	 // create VW dir struture
			}
			
			$newContent = 'public function ' . $title . 'Action() {
						$this->getPageContent();
						$this->view->setLayout("default");
						$this->view->show();
							}}';
			
			if(is_writeable($CTdirStructure)){
				$fileOpen = fopen($CTdirStructure, 'r+b'); // open the file and set write and binary operator
				fseek($fileOpen, "-2", SEEK_END);
				if(!fwrite($fileOpen, $newContent)){
					log::fatal("Unable to write dat to file", $this, "createChildPage()");
				}
			}

			fileHandler::getInstance()->makeDir($VWdirStructure, 0777 ); //create view folder
			fileHandler::getInstance()->copyFile($VWdirStructure, $title . ".php", "view/defaultIndex.php");
			$this->view->result = true;
	}

	public function getParents($parent_id){
		$sql = "SELECT id, name FROM `page` WHERE `id` = $parent_id";
		$result = DBH::getInstance()->query($sql, 'page');

		$parentPages = array();
		while ($parent = mysql_fetch_object($result)) {
    		$parentPages[] = $parent;
		}

		return $parentPages;
	}



	//---------------End Page Create functions------------//

	//-------------- Begin Page edit functions --------------//

	public function getColor(){
		$query = DBH::getInstance()->query("SELECT * FROM color WHERE active = 1");
		$sql = mysql_fetch_assoc($query);
		$this->view->huidigeKleur = $sql['color'];	
	}
	
	public function updateColor(){
		$query = DBH::getInstance()->query("UPDATE color SET active = 0 WHERE active = 1");
		$update = DBH::getInstance()->query("UPDATE color SET active = 1 WHERE color ='".$_POST['color']."'");
	}


	public function announcementsAction(){
		$this->view->title = 'Schagen - Mededeling toevoegen ';
		$this->view->layoutPath = 'template';
		$this->view->templateUrl = 'template';

		$this->view->add_css('back/back-main.css');
		$this->view->setLayout('admin');
		$this->getAnnouncements();
		$this->view->removeResult = $this->removeAnnouncement();
		
		if (isset($_POST['submitAnnouncement'])) {
			$this->view->result = $this->addAnnouncement();
		}
		
		$this->view->show();
	}
	
	public function getAnnouncements(){
		$announcments = DBH::getInstance()->read_all("announcement");
		$this->view->announcements = $announcments;
	}
	
	public function removeAnnouncement(){
		if(isset($_GET['remove'])){
			$whereClause = "id = ".$_GET['remove'];
			if(DBH::getInstance()->delete($whereClause, "announcement")){
				
			}
		}
	}

	public function addAnnouncement() {	
		
			$object = new stdClass();

			$object->title = $_POST['title'];
			$object->content = $_POST['content'];
			//TODO add userid in object
			if(!DBH::getInstance()->create($object, "announcement")){
				return false;
			}
			return true;		
	}

	//-------------- End Page edit functions --------------//
	
	//--------------- Begin menu functions ----------------//
	public function menuAction(){
		$this->view->title = 'Schagen - Menu ';
		
		/*
		 * Here you can create all the call to menu functions :)
		 * 
		 */
		
		$this->view->show();
	}
	//--------------- End menu functions -------------------//	
	
	//---------------Begin User Create functions------------//

	public function adduserAction() {
		$this->view->title = 'Schagen - Gebruiker Toevoegen';
		$this->view->layoutPath = 'template';
		$this->view->templateUrl = 'template';

		$this->view->add_css('back/back-main.css');
		$this->view->setLayout('admin');
		$this->getUsers();
		$this->getGroups();
		$this->view->removeResult = $this->removeUser();
		
		if(isset($_GET['edit'])){
			$this->getUserContent();
		}
		
		if (isset($_POST['submitUser'])) {
			$this->view->result = $this->addUser();
		}
		if(isset($_POST['submitUpdateUser'])){
			$this->updateUser();
		}
		$this->view->show();
	}
	
	public function addUser(){
		
		$object = new stdClass();

			$object->username = $_POST['username'];
			$object->password = md5($_POST['password']);
			$object->email = $_POST['email'];
			$object->groups_id = $_POST['group'];
			//TODO add userid in object
			if(!DBH::getInstance()->create($object, "user")){
				return false;
			}
			return true;	
	}		
	
	public function getUsers(){
		$users = DBH::getInstance()->read_all("user");
		$this->view->users = $users;
	}

	public function getUserWhere($whereClause){
		$users = DBH::getInstance()->read($whereClause, $this->userTable);
		return $users;
	}
	
	public function getUserContent() {
		$whereClause =  $_GET['edit'];
		//Build the Query, run it and fetch it
		$sql = "id = '$whereClause'";
		
		$result = DBH::getInstance()->read($sql, $this->userTable);
		$groupName = DBH::getInstance()->query("SELECT * FROM groups WHERE id = " . $result->groups_id);
		$this->view->usergroupname =  mysql_fetch_object($groupName);
		$this->view->user_content = $result;
	}
	
	public function updateUser(){
		$object->username = $_POST['username'];
		if(!empty($_POST['password'])){
			$object->password = md5($_POST['password']);
		}
		$object->email = $_POST['email'];
		$object->groups_id = $_POST['group'];
		$whereClause = "id = ".$_GET['update'];
		//update db
		if(!DBH::getInstance()->update($object, $whereClause, "user")){
			return false;
		}
		return true;
	}
	
	public function removeUser(){
		if(isset($_GET['remove'])){
			$whereClause = "id = ".$_GET['remove'];
			if(DBH::getInstance()->delete($whereClause, "user")){
				
			}
		}
	}
	
	//---------------End User Create functions------------//
	
	//-----------------Begin Group functions--------------//
	
	public function groupsAction(){
		$this->view->title = 'Schagen - Groepen beheren';
		$this->view->layoutPath = 'template';
		$this->view->templateUrl = 'template';

		$this->view->add_css('back/back-main.css');
		$this->view->setLayout('admin');
		$this->getGroups();
		$this->getPages();
		
		if(isset($_POST['submitCreateGroup'])){
			$this->view->result = $this->addGroup();
		}
		
		if(isset($_GET['edit'])){
			$this->getEditPages();
			$this->getGroupContent();
		}
		
		if(isset($_GET['update'])){
			$this->updateGroup();
		}
		
		if(isset($_GET['remove'])){
			$this->removeGroup();
		}
		$this->view->show();
		
		
	}
	
	public function removeGroup(){
		if(isset($_GET['remove'])){
			$whereClause = "group_id = ".$_GET['remove'];
			$del1 = DBH::getInstance()->delete($whereClause, "editpage");
			$del2 = DBH::getInstance()->delete("id = '".$_GET['remove']."'", "groups");
		}
	}
	public function getGroups(){
		$groups = DBH::getInstance()->read_all("groups");
		$this->view->groups = $groups;
	}
	
	public function getEditPages(){
		$where = "group_id = '".$_GET['edit']."'";
		
		$editpages = DBH::getInstance()->read_all_where($where, "groups");
		//$editpages = DBH::getInstance()->query();
		$this->view->editpages =  $editpages;
	}


	
	public function addGroup(){
		$object = new stdClass();

			$object->name = $_POST['name'];
			$object->admin = $_POST['admin'];
			$object->createpage = $_POST['createpage'];
			
			//TODO add userid in object
			if(!DBH::getInstance()->create($object, "groups")){
				return false;
			}
			
			$sql = "name = '".$object->name."'";
			$resultaat = DBH::getInstance()->read($sql, "groups");
			
			$waarde = explode(",", $_POST['arrayVal']);
			$object2->group_id = $resultaat->id;
			
			for($i=0; $i < sizeof($waarde); $i++)
			{
				$object2->page_id = $waarde[$i];
				if(!DBH::getInstance()->create($object2, "editpage")){
					return false;
				}
			}
			
			return true;	
	}
	
	public function getGroupContent() {
		$whereClause =  $_GET['edit'];
		//Build the Query, run it and fetch it
		$sql = "id = '$whereClause'";
		
		$result = DBH::getInstance()->read($sql, "groups");
		$this->view->group_content = $result;
	}
	
	public function updateGroup(){
		$object = new stdClass();

			$object->name = $_POST['name'];
			$object->admin = $_POST['admin'];
			$object->createpage = $_POST['createpage'];
			$whereClause = "id = ".$_GET['update'];
			
			if(!DBH::getInstance()->update($object, $whereClause, "groups")){
				return false;
			}
			
			$del1 = DBH::getInstance()->delete("group_id ='".$_GET['update']."'", "editpage");
			$sql = "name = '".$object->name."'";
			$resultaat = DBH::getInstance()->read($sql, "groups");
			
			$waarde = explode(",", $_POST['arrayVal']);
			$object2->group_id = $resultaat->id;
			
			for($i=0; $i < sizeof($waarde); $i++)
			{
				$object2->page_id = $waarde[$i];
				if(!DBH::getInstance()->create($object2, "editpage")){
					return false;
				}
			}
			
			return $this->view->updateResult = true;	
	}
	//------------------End Group functions---------------//

	//----------------Begin File upload functions----------//

	public function addfileAction(){
		$this->view->title = 'Schagen - Bestand toevoegen ';
		$this->upload_document();
		$this->getFiles();

		$this->view->show();
	}
	
	public function getFiles(){
		if($_SESSION['isAdmin'] == '1'){
			$result = DBH::getInstance()->read_all("document");
		}else{
			$sql = "'groups_id' = ".$_SESSION['groupId']."";
			$result = DBH::getInstance()->read($sql, "document");
			var_dump($result);
			//var_dump($sql);
		}
		$this->view->files = $result;
		var_dump($_SESSION['groupId']);
	}



	public function upload_document(){
		$uploadFolder = 'documents';
		$file_path = "/uploads/" . $uploadFolder . "/";

    	if(isset ( $_POST['btn_submitFile'] ) AND isset( $_POST['title'] ) AND $_POST['title'] != NULL ) {
	    	if($_POST['title'] == ""){
	    		$this->view->message = "U bent vergeten een title in te vullen";
	    		return;
	    	}
               
    			if(fileHandler::getInstance()->uploadfile( $uploadFolder )){

    				$user = $this->getUserWhere("username = '" . $_SESSION['username'] . "'");	

                    $data = new stdClass();
                    $data->title = $_POST['title'];
                    $data->name = $_FILES['uploadedfile']['name'];
                    $data->url = $file_path . $_FILES['uploadedfile']['name'];
                    $data->visible = $_POST['visible'];
                    $data->groups_id = $_SESSION['groupId'];

                    DBH::getInstance()->create($data ,$this->documentTable);
                    $this->view->result = true;
                }else{
                    $this->view->result = false;
                }
                return;
    	}
    }
//--------------------- Begin booking action -----------------------------//
    public function bookingsAction(){
    	$this->view->title = 'Schagen - Reserveringen';
    	$this->view->layoutPath = 'template';
		$this->view->templateUrl = 'template';

		$this->view->add_css('back/back-main.css');
		$this->view->setLayout('admin');
		$this->getBookings();
		$this->acceptBooking();
		$this->removeBooking();
		$this->countBookings();
		$this->view->show();
    } 

    public function countBookings(){
    	$result = DBH::getInstance()->count("booking");
    	$this->view->allbooking = $result;
    }

    public function getBookings(){
		$bookings = DBH::getInstance()->read_all("booking");
		$this->view->bookings = $bookings;
    }

    public function acceptBooking(){
    	if(array_key_exists('accepted', $_GET)){
    		$bookingId = $_GET['accepted'];
    		
    		$object = new stdClass();
    		$object->accepted = "1";

    		$where = $_GET['accepted'];
    		$whereClause = "`id` = " . $where;
    		DBH::getInstance()->update($object, $whereClause, "booking");
    		$this->view->result = "true";
    		header("Location: ./bookings");
    	}
    }

    public function removeBooking(){
    	if(array_key_exists('remove', $_GET)){
    		$bookingId = $_GET['remove'];
    		$sql = "`id` = " . $bookingId;
    		DBH::getInstance()->delete($sql, "booking");
    		$this->view->result = "true";
    		header("Location: ./bookings");
    	}
    }

   
//------------------- End bookings action ------------------------------//
//------------------- Begin viewbooking action --------------------------//
    public function viewbookingAction(){
    	$this->view->title = 'Schagen - Reserveringen';
		$this->view->layoutPath = 'template';
		$this->view->templateUrl = 'template';

		$this->view->add_css('back/back-main.css');
		$this->view->setLayout('admin');
		$this->getuserBooking();
		$this->acceptBooking();
		$this->view->show();
    }

    public function getuserBooking(){
    	$bookingId = $_GET['id'];

    	$result = DBH::getInstance()->query("SELECT * FROM `booking` WHERE `id` = " . $bookingId);
    	$end = mysql_fetch_object($result);
    	$this->view->userbooking = $end;
    }


//------------------- End view bookings action -----------------------//
//---------------- Begin img functions --------------------------------//

	public function imageuploaderAction(){
		$this->view->title = 'Schagen - Afbeeldingen';
		
		//$this->test();
		$this->uploadImg();
		$this->getThumbs();
		$this->deleteImg();

		$this->view->show();
	}

	public function getThumbs(){
		$result = DBH::getInstance()->read_all("thumbs");
		$this->view->thumbs = $result;

	}

	/*
	* Function to upload and resize the img and create thumbnail
	*
	*/
	public function uploadImg(){
		if (array_key_exists('upload', $_POST)) {
			if(array_key_exists('uploaded_image', $_FILES)){
				$fileName = str_replace(' ', '_', $_FILES['uploaded_image']['name']); // get the file name and replace space with "_"
				$savePath = 'uploads/pictures/' . $fileName;
				$savePathThumb = 'uploads/pictures/thumbs/thumb_' . $fileName;

				SIM::getInstance()->load($_FILES['uploaded_image']['tmp_name']); // load the tmp file into the sim class
				SIM::getInstance()->resizeToWidth(250);
				//SIM::getInstance()->scale(50);
				SIM::getInstance()->save($savePath); //save the resized file
				$this->imgToDb($fileName, $savePath, "images"); // create db row
				$this->createThumb($fileName);
				$this->imgToDb($fileName, $savePathThumb, "thumbs");
				$this->view->result = true;
			}
		}
	}

	public function createThumb($name){
		SIM::getInstance()->resizeToWidth(50);
		SIM::getInstance()->save("uploads/pictures/thumbs/thumb_" . $name);
	}

	public function imgToDb($name, $path, $table){
		$object = new stdClass();
		$object->name  = $name;
		$object->path  = $path;
		DBH::getInstance()->create($object, $table);
	}

	public function deleteImg(){
		if(isset($_GET['file'])){
			$fileName = $_GET['file'];

			Controller::deleteFile("/uploads/pictures/" . $fileName, false, false);
			$whereClause = "`name` = '" . $fileName . "'";
            DBH::getInstance()->delete($whereClause, "images");
            DBH::getInstance()->delete($whereClause, "thumbs");

            $this->view->message = "De afbeelding is succesvol verwijderd!";
            return;
		}
	}

	//------------- end img functions ---------------------//

	public function protectedpageAction(){
		$this->view->title = 'Schagen - Beveiligde pagina';
		$this->view->templateUrl = 'template';

		$this->view->add_css('back/back-main.css');
		$this->view->add_css('back/table-styles.css');
		$this->view->add_css('front/style.css');
		$this->view->setLayout('default');

		$whereClause = "id =". $_GET['id'];
		$table = "page";
		$content = DBH::getInstance()->read($whereClause, $table);
		$this->view->content = $content;
		$this->view->show();
	}
}

